package com.example.blogserver.service.Impl;

import com.alibaba.fastjson.JSON;
import com.example.blogserver.a_utils.MqConstants;
import com.example.blogserver.mapper.ArticleMapper;
import com.example.blogserver.mapper.GoodMapper;
import com.example.blogserver.mapper.UserMapper;
import com.example.blogserver.pojo.Article;
import com.example.blogserver.pojo.Good;
import com.example.blogserver.pojo.User;
import com.example.blogserver.service.ArticleService;
import com.example.blogserver.service.ListService;
import com.example.blogserver.a_utils.Constant;
import com.example.blogserver.a_utils.ResponseBodyMessage;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@SuppressWarnings({"all"})
@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private GoodMapper goodMapper;

    @Autowired
    private ListService listService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RestHighLevelClient client;


    @Override
    public ResponseBodyMessage<User> queryUserIdByBlogId(HttpServletRequest request) {
        Integer blogId = Integer.valueOf(request.getParameter("blogId"));
        Article article = articleMapper.getArticleByBlogId(String.valueOf(blogId));
        User nowUser = listService.queryByAccount(request).getData();
        User user = userMapper.queryUser(article.getUserId());
        if (nowUser.getIdentity() == 0) {
            user = userMapper.queryUser(article.getUserId());
        }
        if (article.getStatus() == 0 && (nowUser.getIdentity() == 1 || nowUser.getIdentity() == 2)) {
            user.setIsApprove(1);
        }
        ResponseBodyMessage responseBodyMessage = new ResponseBodyMessage();
        responseBodyMessage.setStatus(1);
        responseBodyMessage.setMessage("用户信息如下");
        responseBodyMessage.setData(user);
        return responseBodyMessage;
    }

    @Override
    public ResponseBodyMessage<Article> getArticleByBlogId(HttpServletRequest request) {
        ResponseBodyMessage responseBodyMessage = new ResponseBodyMessage();
        //获取身份信息
        String account = (String) request.getSession(false).getAttribute(Constant.USERINFO_SESSION_KEY);
        //判断是邮箱还是账号
        if (account.indexOf('@') != -1) {
            //表明是邮箱
            account = getUserId(account);
        }
        //获取queryString当中的blogId
        Integer blogId = Integer.valueOf(request.getParameter("blogId"));
        //调用服务层获取文章详细内容
        Article article = articleMapper.getArticleByBlogId(String.valueOf(blogId));
        //判断是否为当前用户发布的文章
        if (account.equals(article.getUserId())) {
            //是同一个人
            article.setIsYourBlog(1);
        } else {
            article.setIsYourBlog(0);
        }
        User user = userMapper.queryUser(account);
        if (user.getIdentity() != 1) {
            //管理员审批时对访问量不进行+1
            //对文章阅读数+1
            addConsult(blogId);
            //对作者的被访问量进行+1
            addAuthorRead(article.getUserId());
        }
        responseBodyMessage.setStatus(1);
        responseBodyMessage.setMessage("获取文章内容");
        responseBodyMessage.setData(article);
        return responseBodyMessage;
    }

    @Override
    public ResponseBodyMessage<Boolean> addGood(HttpServletRequest request) {
        ResponseBodyMessage responseBodyMessage = new ResponseBodyMessage();
        //获取文章id
        Integer blogId = Integer.valueOf(request.getParameter("blogId"));
        //获取用户id
        String account = (String) request.getSession(false).getAttribute(Constant.USERINFO_SESSION_KEY);
        //判断是邮箱还是账号
        if (account.indexOf('@') != -1) {
            //表明是邮箱
            account = getUserId(account);
        }
        int status = articleMapper.getArticleByBlogId(String.valueOf(blogId)).getStatus();
        if (status == 0 || status == 2) {
            System.out.println("======>" + status);
            responseBodyMessage.setStatus(-1);
            responseBodyMessage.setMessage("文章未经审核成功，此功能暂不支持~");
            responseBodyMessage.setData(false);
        } else {
            //判断表中是否存在点赞信息
            int ret = checkGood(blogId, account);
            if (ret == 1) {
                //表明存在，则点赞失败
                responseBodyMessage.setStatus(-1);
                responseBodyMessage.setMessage("您已经为这篇文章点过赞了，不可重复点赞哦~");
                responseBodyMessage.setData(false);
            } else {
                //表中不存在，说明未点赞
                //进行点赞处理
                goodMapper.addGood(blogId, account);
                //修改文章的获赞信息
                updateGood(blogId);
                //对作者的获赞量进行+1
                addAuthorGood(account);
                responseBodyMessage.setStatus(1);
                responseBodyMessage.setMessage("点赞成功~");
                responseBodyMessage.setData(true);
            }
        }
        return responseBodyMessage;
    }

    @Override
    public ResponseBodyMessage<Boolean> deleteArticleByBlogId(HttpServletRequest request) {
        ResponseBodyMessage responseBodyMessage = new ResponseBodyMessage();
        //获取queryString当中的文章id
        String blogId = request.getParameter("blogId");
        //根据文章Id获取到文章的被访问量和获赞量
        Article article = getArticleByBlogId(request).getData();
        //获取被访问次数
        int read = article.getConsult();
        //获取文章的获赞量
        int good = article.getPraise();
        //调用服务层代码根据文章Id删除文章
        articleMapper.deleteArticleByBlogId(blogId);
        //修改用户的访问量和获赞量
        updateUserMse(read, good, article.getUserId());
        //删除获赞表的文章获赞信息
        deleteGood(blogId);
        //查看文章状态
        int status = article.getStatus();
        if (status == 0) {
            //审批中
            userMapper.updateUserSumExamine(article.getUserId());
        } else if (status == 2) {
            //审批不通过
            userMapper.redUserSumFail(article.getUserId());
        } else {
            //已发布
            userMapper.redUserSumPublished(article.getUserId());
        }
        //对作者的文章数进行-1
        subTextCount(article.getUserId());
        rabbitTemplate.convertAndSend(MqConstants.ARTICLE_EXCHANGE, MqConstants.ARTICLE_DELETE_KEY, article.getId());
        responseBodyMessage.setStatus(1);
        responseBodyMessage.setMessage("删除成功~");
        responseBodyMessage.setData(true);
        return responseBodyMessage;
    }

    @Override
    public ResponseBodyMessage<String> checkArticle(HttpServletRequest request) {
        ResponseBodyMessage<String> responseBodyMessage = new ResponseBodyMessage<>();
        String blogId = request.getParameter("blogId");
        Article article = articleMapper.getArticleByBlogId(blogId);
        String userId = article.getUserId();
        String result = request.getParameter("result");
        if (result.equals("ok")) {
            //审核通过
            //1.先将文章状态改为已发布 status = 1
            articleMapper.updateArticleStatus(blogId, 1);
            //2.修改用户的已发布文章数和审核中状态数 published+1 examine-1
            userMapper.updateUserSumPublished(userId);
            userMapper.updateUserSumExamine(userId);
        } else if(result.equals("no"))  {
            //审核不通过
            //1.先将文章状态改为审核不通过 status = 2
            articleMapper.updateArticleStatus(blogId, 2);
            //2.修改用户的审核中状态数和审核不通过状态数 examine-1 fail+1
            userMapper.updateUserSumExamine(userId);
            userMapper.updateUserSumFail(userId);
        }
        responseBodyMessage.setMessage("审批成功~");
        responseBodyMessage.setData("审批成功~");
        responseBodyMessage.setStatus(1);
        return responseBodyMessage;
    }

    @Override
    public void deleteDocumentById(Long id) {
        try {
            // 1. 准备Request
            DeleteRequest request = new DeleteRequest("article", String.valueOf(id));
            // 2. 发送请求
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void InsertOrUpdateDocumentById(Long id) {
        try {
            // 0. 根据id查询文章数据
            Article article = articleMapper.getArticleByBlogId(String.valueOf(id));
            // 1. 准备request对象
            IndexRequest request = new IndexRequest("article").id(String.valueOf(article.getId()));
            // 2. 准备JSON文档
            request.source(JSON.toJSONString(article), XContentType.JSON);
            // 3. 发送请求
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据邮箱获取用户id
     */
    public String getUserId(String account) {
        User user = userMapper.queryUser(account);
        return user.getUserid();
    }

    /**
     * 对文章阅读数进行+1
     */
    public void addConsult(Integer blogId) {
        articleMapper.addConsult(blogId);
    }

    /**
     * 判断点赞表中是否存在点赞信息
     */
    public int checkGood(Integer blogId, String account) {
        Good good = goodMapper.checkGood(blogId, account);
        if (good == null) {
            //说明不存在
            return -1;
        } else {
            return 1;
        }
    }

    /**
     * 对文章的获赞量进行修改
     */
    public void updateGood(Integer blogId) {
        articleMapper.updateGood(blogId);
    }

    /**
     * 对用户表的获赞字段和访问字段进行修改
     */
    public void updateUserMse(int read, int good, String userId) {
        userMapper.updateRead(read, userId);
        userMapper.updateGood(good, userId);
    }

    /**
     * 删除获赞表中BlogId为XXX的信息
     */
    public void deleteGood(String blogId) {
        goodMapper.deleteData(blogId);
    }


    /**
     * 对作者的访问量进行+1
     */
    public void addAuthorRead(String userId) {
        userMapper.addAuthorRead(userId);
    }

    /**
     * 对作者的获赞量进行+1
     */
    public void addAuthorGood(String account) {
        userMapper.addAuthorGood(account);
    }


    /**
     * 对用户的文章数进行减一
     */
    public void subTextCount(String userId) {
        userMapper.subTextCount(userId);
    }
}
